#include"Queue.h"
#include<assert.h>
void QueueInit(Queue* pq)                                                    
{
	assert(pq);
	pq->tail = NULL;  
	pq->head = NULL;
}

void QueueDestroy(Queue* pq)             //销毁要依次遍历每个结点并释放内存                                   
{	
    assert(pq);
	QueueNode * cur = pq->head;         
	while (cur != NULL)
	{
		QueueNode* next = cur->next;         //新定义一个next,帮助cur依次遍历pq
		free(cur);                        
		cur = next;     //不用置空,局部变量
	}
	pq->head = NULL;   //头尾结点要置空
	pq->tail = NULL;
}

void QueuePush(Queue* pq, QDataType x)    //入队,新创建一个新结点,让为指针指向新结点,但若尾指针为空,就没有next,所以要分情况
{
	assert(pq);
	QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
	if (newnode == NULL)       
	{
		printf("malloc fail\n");
		exit(-1);
	}
	newnode->val = x;
	newnode->next = NULL;
	if (pq->head == NULL)   //队列为空时直接将新指针赋值给头尾指针
	{
		pq->head = pq->tail = newnode;
	}
	else                    //不为空则让尾指针指向新指针
	{
		pq->tail->next = newnode;
		pq->tail = newnode;
	}

}

void QueuePop(Queue* pq)                                           //出队
{
	assert(pq);
	assert(pq->head);
	QueueNode* del = pq->head;
	pq->head = pq->head->next;
	free(del);
	del = NULL;
	if (pq->head == NULL)    //前面已经判断了队列不为空,这时候如果head还为空就说明已经删完了,此时Head为tail的next,head已经置空,但tail只是被
	{                        // free,没有被置空
		pq->tail = NULL;
	}
}

void QueuePirnt(Queue* pq)                                          //打印
{
	QueueNode* cur = pq->head;
	while (cur)
	{
		printf("%d ", cur->val);
		cur = cur->next;
	}
	printf("\n");
}

QDataType QueueFront(Queue* pq)                                   //头结点的值
{
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->head->val;
}

QDataType QueueBack(Queue* pq)                                    //尾结点的值
{
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->tail->val;
}
bool QueueEmpty(Queue* pq)                                        //判断是否为空
{
	assert(pq);
	return pq->head == NULL;
}

int QueueSize(Queue* pq)                                        //结点数量
{
	int size = 0;
	QueueNode* cur = pq->head;
	while (cur)
	{
		cur = cur->next;
		size++;
	}
	return size;
}
